from fastapi import APIRouter
from pydantic import BaseModel

from DataModels.database import User
from DataModels.share import RespResultCode, RespInfo, StatusInfo, TokenPayload
from utils.share import timestamp
from utils.token import generate_token

verify_router = APIRouter(prefix="/verify")


class SMSVerifyRequest(BaseModel):
    phone: str
    code: str


@verify_router.post("", response_model=RespInfo)
async def verify(data: SMSVerifyRequest):
    """
    此端点返回的 临时密文（code）本质上就是一个 JWT 凭证，
    和前端请求时，在请求头中携带的 token 是一致的。
    """
    user = await User.find_one(User.phone == data.phone)
    if not user:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.PhoneNotFound,
                msg="未找到手机号",
            )
        )

    if data.code == user.code:
        if user.verified:
            return RespInfo(
                status=StatusInfo(
                    code=RespResultCode.CodeExpire,
                    msg="验证码已过期",
                )
            )
        user.verified = True
        await user.save()  # type: ignore

        return RespInfo(
            code=generate_token(TokenPayload(phone=user.phone, createTime=timestamp())),
            status=StatusInfo(
                code=RespResultCode.Success,
                msg="验证码验证成功",
            ),
        )
    else:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.CodeErr,
                msg="验证码错误",
            )
        )
